package com.xsmart.common.services;

import com.xsmart.common.constant.RedisKeyConstant;
import com.xsmart.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LoginTokenService {
    @Autowired
    RedisUtil redisUtil;

    public String generalTokenStr() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public void saveLoginToken(String token, Map<String, Object> userInfo, boolean isRemember) {
        String tokenKey = RedisKeyConstant.SESSION_USER_TOKEN_PREFIX + token;
        Map<String, String> userInfoMap = new HashMap<>();
        for (String key : userInfo.keySet()) {
            userInfoMap.put(key, String.valueOf(userInfo.get(key)));
        }
        redisUtil.hmSetWithStrKey(tokenKey, userInfoMap);
        if (isRemember) {
            redisUtil.expire(tokenKey, 30000);
        } else {
            redisUtil.expire(tokenKey, 100000);
        }
    }

    public void clearLoginToken(String token) {
        String tokenKey = RedisKeyConstant.SESSION_USER_TOKEN_PREFIX + token;
        redisUtil.del(tokenKey);
    }

    public Map<String, String> getLoginUserInfoByToken(String token) {
        String tokenKey = RedisKeyConstant.SESSION_USER_TOKEN_PREFIX + token;
        return redisUtil.getHashByKey(tokenKey);
    }

    public boolean checkUserLoginByToken(String token) {
        String tokenKey = RedisKeyConstant.SESSION_USER_TOKEN_PREFIX + token;
        return redisUtil.exists(tokenKey);
    }
}
